var tableUserGrouphangka
var roamingindatatable
var roamingoutdatatable
var Websitetatable

var d;
//查询参数

var param = new Object({
	init:function(){
		this.beginDate = ''
		this.endDate = ''
		this.dimension = ''
		this.userGroup = ''
		this.terminal_type = ''
		this.terminal_name = ''
	},
	setDimensionParam:function(dimension){
		switch(dimension) {
			case 'usergrouptype' :
				this.userGroup = $('#groupId').val()
				break
			case 'terminal' :
				this.terminal_type = $('#terminal_type').val()
				this.terminal_name = $('#terminal_name').val()
				break
		}
	},
	setParam:function(){
		this.init()
		
		this.beginDate = $('#startTime').val()
		this.endDate = $('#endTime').val()
		this.dimension = $('input:radio[name="ab"]:checked').val();
		this.setDimensionParam(this.dimension)
	}
});


$(function() {
	// getList();
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});
	
	 $("#groupId").combobox();
	    //终端
	 $("#terminal_type").combobox({
			select:function(event,ui){
				var terminalBrand = $(this).val();
				$.ajax({
					url : '../../feature/terminalUE/terminalModelInfos?terminalBrand='
							+ terminalBrand,
					type : 'POST',
					dataType : 'JSON',
					error : function() {
						alert('Error loading data!');
					},
					success : function(msg) {
						
						$("#terminal_name").empty();
						$("#terminal_name").append("<option value=''>全部</option>");
						var list = msg.terminalModelList;
						$.each(eval(list), function(i, item) {
								$("<option value='" + item.terminal_model + "'>" + item.terminal_model+ "</option>").appendTo($("#terminal_name"));
						});
					}
				});
			},
			width:60
		});
	    $("#terminal_name").combobox();
    
	up_flow_count_char = echarts.init(document.getElementById('up_flow_count_'));
	down_flow_count_char = echarts.init(document.getElementById('down_flow_count_'));
	get_gauge_char(up_flow_count_char,0)
	get_gauge_char(down_flow_count_char,0)
	netTimePsLine = echarts.init(document.getElementById('netTimePsLine'));
	netQualityChar = echarts.init(document.getElementById('netQualityPsLine'));
	kqiPsLineChar = echarts.init(document.getElementById('kqiPsLine'));
})

//初始化init
function get_gauge_char(charvar,data) {

	var option = {
			tooltip : {
				formatter : "{a} <br/>{b} : {c}TB"
			},
			series : [ {
				name : '业务指标',
				type : 'gauge',
				min:0,
	            max:100,
				detail : {
					formatter : '{value}TB',
					textStyle: {
						fontSize: 15
			        }
				},
				data : [ {
					value : data,
					name : ''
				} ],
				splitNumber : 5,
				axisLine : { // 坐标轴线

					lineStyle : { // 属性lineStyle控制线条样式

						color : [ [ 0.2, '#44B7D3' ], [ 0.8, '#6B6455' ],[ 1, '#E42B6D' ] ],
						width : 10
					}
				},
				axisTick : { // 坐标轴小标记

					splitNumber : 10, // 每份split细分多少段

					length : 15, // 属性length控制线长

					lineStyle : { // 属性lineStyle控制线条样式

						color : 'auto'
					}
				},
				splitLine : { // 分隔线

					length : 22, // 属性length控制线长

					lineStyle : { // 属性lineStyle（详见lineStyle）控制线条样式

						color : 'auto'
					}
				},
				pointer : {
					width : 5
				}
			} ]
		};
	
	charvar.clear();
	charvar.showLoading({
		text : '正在努力的读取数据中...'
	});
	charvar.setOption(option, true);
	charvar.hideLoading();
}


//查询 所用的函数

function getList() {
	
	if(!check_date($("#startTime").val(),$("#endTime").val())){
		alert("请输入您需要查询间隔为一天的日期!")
	}else {
		
		$("#startTime_goto").val($("#startTime").val())
		$("#endTime_goto").val($("#endTime").val())
        $("#groupName_goto").val($("#groupId option:selected").val())
        $("#terminalBrandId_goto").val($("#terminalBrandId option:selected").val())
	
		var dimension = $('input:radio[name="ab"]:checked').val();
         
	    switch(dimension) {
		case 'usergrouptype' :
			 $("#userGroup_").html($("#groupId").find("option:selected").text());
			break
		case 'terminal' :
			var terminal_type = $('#terminal_type').val();
			var terminal_name = $('#terminal_name').val();
			$("#userGroup_").html(terminal_type +" "+ terminal_name+":");
			break
	    }
        
		     getUserNum();
	         getusergroupTraffic();
			 getServiceType();
			 getCommunity();
		     getVisitedWebsite();
			 initNetTimeChar();
			 initnetQualityPsLineChar();
			 initkqiChar();
		 
		  var group_hangka=$('#groupId').val();
		  if(6 == group_hangka && "usergrouptype"==dimension){
           $('#hangka').show();
           getUserGroupHangka();
		 }else {
			 $('#hangka').hide(); 
		 }
	}
}



function getUserNum() {
	param.setParam();
    $.ajax({
        type : "POST",
        url : "../../excavantionAnalysis/usergroupanalysis/getUserNum?rand="
				+ Math.random(),
        data : {
        	 "param" : JSON.stringify(param)
        },
		dataType : "json",
		success : function(data) {
			//console.log(data)
			if(data["charData"][0].user_num==undefined || data["charData"][0] == null){
				$("#usernum").html(0);
			}else{
				$("#usernum").html(data["charData"][0].user_num);
			}
		}
	});
}
// 获取用户组 上下行 流量
function getusergroupTraffic() {
	
	param.setParam();
    $.ajax({
        type : "POST",
        url : "../../excavantionAnalysis/usergroupanalysis/getusergroupTraffic?rand="
				+ Math.random(),
        data : {
        	 "param" : JSON.stringify(param)
        },
		dataType : "json",
		success : function(data) {
			//console.log(data)
			//{"charData":[{"input_octets":16.8647,"output_octets":4.0135}]}
			//$("#usernum").html(data["allData"][0].usernum);
			if(data.charData[0].input_octets==undefined){
				$("#up_flow_count").html(0+"TB");
				get_gauge_char(up_flow_count_char,0);
			}else{
				$("#up_flow_count").html(data["charData"][0].input_octets+"TB");
				get_gauge_char(up_flow_count_char,data["charData"][0].input_octets)
			}
			
			if(data["charData"][0].output_octets==undefined){
				$("#down_flow_count").html(0+"TB");
				get_gauge_char(down_flow_count_char,0);
			}else{
				$("#down_flow_count").html(data["charData"][0].output_octets+"TB");
				get_gauge_char(down_flow_count_char,data["charData"][0].output_octets);
			}
		}
	});
}

/**
 * 行卡用户分析 
 * 
 */
function getUserGroupHangka() {
	param.setParam();
	$("#tableUserGrouphangka tbody tr").remove();
	if (tableUserGrouphangka == undefined || tableUserGrouphangka == "undefined" || tableUserGrouphangka == null) {
	} else {
		tableUserGrouphangka.destroy();
	}
	tableUserGrouphangka = $('#tableUserGrouphangka').DataTable(
			{
				"aoColumnDefs" : [ {
					sDefaultContent : '',
					aTargets : [ '_all' ]
				} ],
				"bPaginate" : true, // 翻页功能
				"iDisplayLength" : 50,
				"bLengthChange" : false, // 改变每页显示数据数量
				"bFilter" : false, // 过滤功能
				"ordering": true, //排序功能
				"bSort" : true, // 排序功能
				"bInfo" : true,// 页脚信息
				"bAutoWidth" : true,// 自动宽度
				"iDisplayLength" : 50,
				// "sPaginationType": "full_numbers",//显示分页的样式
				// 还有simple_numbers等
//				"sScrollX" : "100%",
				"sScrollXInner" : "110%",
				"bScrollCollapse" : true,
				"oLanguage" : {
					"sLengthMenu" : "每页显示 _MENU_条",
					"sZeroRecords" : "没有找到符合条件的数据",
					"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
					"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
					"sInfoEmpty" : "没有记录",
					"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
					"sSearch" : "搜索：",
					"oPaginate" : {
						"sFirst" : "首页",
						"sPrevious" : "前一页",
						"sNext" : "后一页",
						"sLast" : "尾页"
					}
				},
				"bProcessing" : true,
				"bServerSide" : true,
		"sAjaxSource" : "../../excavantionAnalysis/usergroupanalysis/getHangkaAnalysis",
		"fnServerData" : function(sSource, aoData, fnCallback) {
			$.ajax({
				"type" : "post",
				"contentType" : "application/x-www-form-urlencoded",
				"url" : sSource,
				"dataType" : "json",
				"data" : {
					"aoData" : JSON.stringify(aoData),
					"param" : JSON.stringify(param)
				}, // 以json格式传递
				"success" : function(resp) {
					fnCallback(resp.pageDate);
					d = resp.allData;
				}
			});
		},
		columns : [ {
			data : "apn"
		}, {
			data : "apn_name"
		}, {
			data : "traffic_sum"
		}, {
			data : "avg_traffic"
		}, {
			data : "atta_ratio"
		}, {
			data : "tau_ratio"
		}, {
			data : "session_ratio"
		}, {
			data : "tcp_ratio"
		}, {
			data : "download_speed"
		}, {
			data : "dns_ratio"
		} ]
	});
}


/**
 * 小区上网
 * 
 */

function getCommunity() {
	
	param.setParam();

	$("#tableonline tbody tr").remove();
	if (roamingindatatable == undefined || roamingindatatable == "undefined" || roamingindatatable == null) {
	} else {
		roamingindatatable.destroy();
	}
	roamingindatatable = $('#tableonline').DataTable(
			{
				"aoColumnDefs" : [ {
					sDefaultContent : '',
					aTargets : [ '_all' ]
				} ],
				"bPaginate" : true, // 翻页功能
				"iDisplayLength" : 50,
				"bLengthChange" : false, // 改变每页显示数据数量
				"bFilter" : false, // 过滤功能
				"ordering": true, //排序功能
				"bSort" : true, // 排序功能
				"bInfo" : true,// 页脚信息
				"bAutoWidth" : true,// 自动宽度
				"iDisplayLength" : 50,
				// "sPaginationType": "full_numbers",//显示分页的样式
				// 还有simple_numbers等
//				"sScrollX" : "100%",
				"sScrollXInner" : "110%",
				"bScrollCollapse" : true,
				"oLanguage" : {
					"sLengthMenu" : "每页显示 _MENU_条",
					"sZeroRecords" : "没有找到符合条件的数据",
					"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
					"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
					"sInfoEmpty" : "没有记录",
					"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
					"sSearch" : "搜索：",
					"oPaginate" : {
						"sFirst" : "首页",
						"sPrevious" : "前一页",
						"sNext" : "后一页",
						"sLast" : "尾页"
					}
				},
				"bProcessing" : true,
				"bServerSide" : true,
		"sAjaxSource" : "../../excavantionAnalysis/usergroupanalysis/getCommunity",
		"fnServerData" : function(sSource, aoData, fnCallback) {
			$.ajax({
				"type" : "post",
				"contentType" : "application/x-www-form-urlencoded",
				"url" : sSource,
				"dataType" : "json",
				"data" : {
					"aoData" : JSON.stringify(aoData),
					"param" : JSON.stringify(param)
				}, // 以json格式传递
				"success" : function(resp) {
					fnCallback(resp.pageDate);
					d = resp.allData;
				}
			});
		},
		columns : [ {
			data : "cell_name"
		}, {
			data : "cell_id"
		}, {
			data : "traffic_sum"
		}, {
			data : "delay"
		}, {
			data : "business_speed"
		}]
	});
}
 
/**
 * 业务喜好
 * 
 */

function getServiceType() {
	
					param.setParam();
				    
					$("#tablebehavor tbody tr").remove();
					if (roamingoutdatatable == undefined || roamingoutdatatable == "undefined" || roamingoutdatatable == null) {
					} else {
						roamingoutdatatable.destroy();
					}
					roamingoutdatatable = $('#tablebehavor').DataTable(
							{
								"aoColumnDefs" : [ {
									sDefaultContent : '',
									aTargets : [ '_all' ]
								} ],
								"bPaginate" : true, // 翻页功能
								"iDisplayLength" : 50,
								"bLengthChange" : false, // 改变每页显示数据数量
								"bFilter" : false, // 过滤功能
								"ordering": true, //排序功能
								"bSort" : true, // 排序功能
								"bInfo" : true,// 页脚信息
								"bAutoWidth" : true,// 自动宽度
								"iDisplayLength" : 50,
								// "sPaginationType": "full_numbers",//显示分页的样式
								// 还有simple_numbers等
//								"sScrollX" : "100%",
								"sScrollXInner" : "110%",
								"bScrollCollapse" : true,
								"oLanguage" : {
									"sLengthMenu" : "每页显示 _MENU_条",
									"sZeroRecords" : "没有找到符合条件的数据",
									"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
									"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
									"sInfoEmpty" : "没有记录",
									"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
									"sSearch" : "搜索：",
									"oPaginate" : {
										"sFirst" : "首页",
										"sPrevious" : "前一页",
										"sNext" : "后一页",
										"sLast" : "尾页"
									}
								},
								"bProcessing" : true,
								"bServerSide" : true,
						"sAjaxSource" : "../../excavantionAnalysis/usergroupanalysis/getServiceType",
						"fnServerData" : function(sSource, aoData, fnCallback) {
							$.ajax({
								"type" : "post",
								"contentType" : "application/x-www-form-urlencoded",
								"url" : sSource,
								"dataType" : "json",
								"data" : {
									"aoData" : JSON.stringify(aoData),
									"param" : JSON.stringify(param)
								}, // 以json格式传递
								"success" : function(resp) {
									fnCallback(resp.pageDate);
									d = resp.allData;
								}
							});
						},
						columns : [{
							data : "business_group"
						}, {
							data : "traffic_sum"
						}, {
							data : "delay"
						}, {
							data : "business_speed"
						}]
					});
}



/**
 * 访问网站
 * 
 */

function getVisitedWebsite() {
	
					param.setParam();
				    
				
					$("#tablewebsite tbody tr").remove();
					if (Websitetatable == undefined || Websitetatable == "undefined" || Websitetatable == null) {
					} else {
						Websitetatable.destroy();
					}
					Websitetatable = $('#tablewebsite').DataTable(
							{
								"aoColumnDefs" : [ {
									sDefaultContent : '',
									aTargets : [ '_all' ]
								} ],
								"bPaginate" : true, // 翻页功能
								"iDisplayLength" : 50,
								"bLengthChange" : false, // 改变每页显示数据数量
								"bFilter" : false, // 过滤功能
								"ordering": true, //排序功能
								"bSort" : true, // 排序功能
								"bInfo" : true,// 页脚信息
								"bAutoWidth" : true,// 自动宽度
								"iDisplayLength" : 50,
								// "sPaginationType": "full_numbers",//显示分页的样式
								// 还有simple_numbers等
//								"sScrollX" : "100%",
								"sScrollXInner" : "110%",
								"bScrollCollapse" : true,
								"oLanguage" : {
									"sLengthMenu" : "每页显示 _MENU_条",
									"sZeroRecords" : "没有找到符合条件的数据",
									"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
									"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
									"sInfoEmpty" : "没有记录",
									"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
									"sSearch" : "搜索：",
									"oPaginate" : {
										"sFirst" : "首页",
										"sPrevious" : "前一页",
										"sNext" : "后一页",
										"sLast" : "尾页"
									}
								},
								"bProcessing" : true,
								"bServerSide" : true,
						"sAjaxSource" : "../../excavantionAnalysis/usergroupanalysis/getWebSite",
						"fnServerData" : function(sSource, aoData, fnCallback) {
							$.ajax({
								"type" : "post",
								"contentType" : "application/x-www-form-urlencoded",
								"url" : sSource,
								"dataType" : "json",
								"data" : {
									"aoData" : JSON.stringify(aoData),
									"param" : JSON.stringify(param)
								}, // 以json格式传递
								"success" : function(resp) {
									fnCallback(resp.pageDate);
									d = resp.allData;
								}
							});
						},
						columns : [{
							data : "web_site"
						}, {
							data : "sp"
						}, {
							data : "request_num"
						}, {
							data : "traffic_sum"
						}, {
							data : "output_octets"
						}, {
							data : "input_octets"
						}, {
							data : "output_packet"
						}, {
							data : "input_packet"
						}]
					});
}

// 以下图表相关的 

/**
 * 图表展示函数
 */

/**
 * 业务KQI
 * 
 */
function initkqiChar() {

	param.setParam();
	
	// 查询
	kqiPsLineChar.clear();
	kqiPsLineChar.showLoading({
		text : '正在努力的读取数据中...'
	});
	$.ajax({
		type : "POST",
		url : "../../excavantionAnalysis/usergroupanalysis/getkqichar?rand="
				+ Math.random(),
		dataType : "json",
		"data" : {
			"param" : JSON.stringify(param)
		},
		success : function(data) {
			kqiPsLineChar.setOption(data, true);
			kqiPsLineChar.hideLoading();
		}
	});
}


function initNetTimeChar() {
	param.setParam();
	// 查询
	netTimePsLine.clear();
	netTimePsLine.showLoading({
		text : '正在努力的读取数据中...'
	});
	$.ajax({
		type : "POST",
		url : "../../excavantionAnalysis/usergroupanalysis/getnettimechar?rand="
				+ Math.random(),
		dataType : "json",
		"data" : {
			"param" : JSON.stringify(param)
		},
		success : function(data) {
			netTimePsLine.setOption(data, true);
			netTimePsLine.hideLoading();
		}
	});
}

function initnetQualityPsLineChar() {
	
	param.setParam();
	// 查询
	netQualityChar.clear();
	netQualityChar.showLoading({
		text : '正在努力的读取数据中...'
	});
	$.ajax({
		type : "POST",
		url : "../../excavantionAnalysis/usergroupanalysis/getnetqualitychar?rand="
				+ Math.random(),
		dataType : "json",
		"data" : {
			"param" : JSON.stringify(param)
		},
		success : function(data) {
			netQualityChar.setOption(data, true);
			netQualityChar.hideLoading();
		}
	});
}

/**
 * 重置函数
 * 
 */
function resetQueryForm() {
	$('#queryForm')[0].reset();
}

function goToURLUsergroupDetails() {
	var startTime_goto = $("#startTime_goto").val()
	var endTime_goto = $("#endTime_goto").val()
	var groupName_goto = $("#groupName_goto").val()
	var terminalBrandId_goto = $("#terminalBrandId_goto").val()
	
	if(!check_date($("#startTime").val(),$("#endTime").val())){
		alert("请输入您需要查询间隔为一天的日期!")
		return
	}  
	var dimension = $('input:radio[name="ab"]:checked').val();
	if(dimension =="usergrouptype"){
		 linkTab("用户性能分析","/businessAnalysis/userPerformance/getInfosByGroupInfo?beginDate=" + startTime_goto + "&endDate=" + endTime_goto +"&groupId=" + groupName_goto)
	}else{
		linkTab("用户性能分析","/businessAnalysis/userPerformance/getInfosByGroupInfo?beginDate=" + startTime_goto + "&endDate=" + endTime_goto +"&terminalBrandId=" + terminalBrandId_goto)
	}
	
}


